/**
 * refactoring by zhouli on 2019/3/14.
 * 在线客服与反馈(左下角)
 */
import React from 'react';
import {connect} from 'react-redux';
import {Button, Icon, Spin, Input, Tooltip, List, Popover} from 'antd';
import {messages} from 'share/common';
import 'styles/main/components/mode-menu.scss'
import mainService from 'containers/main.service';
import debounce from "lodash.debounce";
import errorMessage from "share/errorMessage";
import trial from "images/trail.png"

class ModeMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      loading: false,
      hasMore: true,
      visible: false,
      page: 0,
      size: 20,
      total: 0,
      availableCompanyList: [props.company],
      keyword: ''
    };
    this.getAvailableCompany = debounce(this.getAvailableCompany,500);
  }

  componentWillMount() {
    this.getAvailableCompany();
  }

  //获取公司列表
  getAvailableCompany = () => {
    const { user, company } = this.props;
    //没有接口权限
    if (user.enableNewPermission && !user.hasTenantRole) {
      return;
    }
    if (!user.enableNewPermission && !this.checkAuthorities('ROLE_TENANT_ADMIN')) {
      return;
    }
    const { page, size, hasMore, availableCompanyList, keyword } =this.state;
    let params = { page, size, keyword };
    this.setState({ loading: true });
    hasMore && mainService.getAvailableCompany(params).then(res => {
      //保证默认公司排在第一个，删掉后续查出来的
      !keyword && res.data.filter((i, index) => (i.companyOID === company.companyOID) && (res.data.splice(index, 1)));
      this.setState({
        loading: false,
        hasMore: (page + 1) * size < Number(res.headers['x-total-count']),
        page: page + 1,
        total: Number(res.headers['x-total-count']),
        availableCompanyList: availableCompanyList.concat(res.data)
      });
    }).catch (err => {
      errorMessage(err || message('common.error1'));
      this.setState({ loading: false });
    });
  };

  onSearchCompany = e => {
    const { company } = this.props;
    this.setState({
      keyword: e.target.value,
      availableCompanyList: e.target.value ? [] : [company],
      page: 0,
      hasMore: true,
    }, this.getAvailableCompany);
  };

  toggleMenuCollapse = () => {
    const { onCollapse } = this.props;
    this.setState({ collapsed: !this.state.collapsed }, () => onCollapse(this.state.collapsed));
  };

  renderMenuList = () => {
    const { loading, hasMore, availableCompanyList, keyword } = this.state;
    const { tenantMode, loginCompany, onChangeCompany, onChangeMode, spinning } = this.props;
    return (
      <Spin spinning={spinning}>
        <div className='current-mode'>
          <span className='highlight-default default-color-font'>{messages('main.key1')/*当前*/}</span>
          { tenantMode ? messages('dashboard.key87'/*集团模式*/) : loginCompany.name }
        </div>
        { !tenantMode && <Button type='link' icon="swap" onClick={() => onChangeMode(null, true)}>{messages('main.key2')/*切换到集团模式*/}</Button>}
        <div style={{padding: '12px 20px'}}>
          <Input
            prefix={<Icon type="search" className='font-subtitle'/>}
            placeholder={messages('main.key3')/*请输入公司/代码名称*/}
            value={keyword}
            onChange={this.onSearchCompany}
          />
        </div>
        { availableCompanyList.length ? (
          <div
            className='company-list'
            style={{maxHeight: tenantMode ? 'calc(100vh - 102px)' : 'calc(100vh - 138px)'}}
            onScrollCapture={() => this.getAvailableCompany()}
          >
            <List
              dataSource={availableCompanyList}
              renderItem={item => (
                <List.Item
                  key={item.id}
                  onClick={() => onChangeCompany(item.id)}
                  className={(!tenantMode && item.companyCode === loginCompany.companyCode) ? 'active' : ''}>
                  <div className='name'>{item.name}</div>
                  <div className='code'>{item.companyCode}</div>
                </List.Item>
              )}
            />
          </div>
        ) : ''}
        { loading && hasMore && (
          <div className="loading-container">
            <Spin />
          </div>
        )}
      </Spin>
    )
  };

  renderMenuHead() {
    const { collapsed } = this.state;
    const { tenantMode, loginCompany, adminMode } = this.props;
    return (
      <div className="company-name">
        <Tooltip
          title={collapsed ? messages('main.key4')/*展开导航*/ : messages('main.key5')/*收起导航*/}
          placement='bottomLeft'
        >
          <span>
            <Icon
              type={collapsed ? 'menu-unfold' : 'menu-fold'}
              onClick={this.toggleMenuCollapse}
            />
          </span>
        </Tooltip>
        {
          tenantMode && adminMode ? (collapsed ? messages('main.key6')/*集团*/ : messages('dashboard.key87'/*集团模式*/)) : loginCompany.name
        }
      </div>
    );
  }

  render() {
    const { collapsed } = this.state;
    const { user, userPermission, tenant, adminMode } = this.props;
    let tenantAuth = user.enableNewPermission ? userPermission.hasTenantRole : this.checkAuthorities('ROLE_TENANT_ADMIN');
    return (
      <div className='mode-menu'>
        {
          !tenant.licensed && tenant.status === "TRAIL" &&
          <div className="trial-info">
            <img src={trial} style={{width: 13, height: 13, marginRight: 4}}/>{messages('main.key106')/*试用中*/}
          </div>
        }
        {
          tenantAuth && adminMode ? (
            <Popover
              content={this.renderMenuList()}
              placement="rightTop"
              overlayClassName={`mode-menu-popover ${collapsed ? 'collapsed' : ''}`}
            >
              {this.renderMenuHead()}
            </Popover>
          ) : (
            this.renderMenuHead()
          )
        }
      </div>
    )
  }
}

ModeMenu.propTypes = {
  onCollapse: React.PropTypes.func,
  onChangeCompany: React.PropTypes.func,
  onChangeMode: React.PropTypes.func
};

ModeMenu.defaultProps = {};

ModeMenu.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    tenantMode: state.main.tenantMode,//集团模式
    adminMode: state.main.adminMode,//管理员模式
    loginCompany: state.login.loginCompany,
    company: state.login.company,
    userPermission: state.login.userPermission,
    tenant: state.login.tenant,
  }
}

export default connect(mapStateToProps)(ModeMenu);

